package com.winit.openapi.util;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.winit.openapi.model.RequestMsg;



public class SignValid {
	
	/**
	 * 
	 * GET TOKEN SQL
	 * select u.token from ad_user u where u.name = 'rebecca';
	 * 
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String s = IOUtils.toString(SignValid.class.getResourceAsStream("SignValid.txt"),"UTF-8");
		RequestMsg requestMsg = JSONObject.parseObject(s, RequestMsg.class);
		
		/*************** 修改签名为对应用户的token ****************/
 		String jsonStr = decode(buildJsonStr(requestMsg,"0316D2A3FD07B0D1F347B5931D9B88FC"));
		System.out.println(jsonStr);
		
		String sign = MD5Util.getMd5(jsonStr);
		System.out.println(sign);
		
	}
	
	public static String decode(String unicodeStr) {  
	    if (unicodeStr == null) {  
	        return null;  
	    }  
	    StringBuffer retBuf = new StringBuffer();  
	    int maxLoop = unicodeStr.length();  
	    for (int i = 0; i < maxLoop; i++) {  
	        if (unicodeStr.charAt(i) == '\\') {  
	            if ((i < maxLoop - 5)  
	                    && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr  
	                            .charAt(i + 1) == 'U')))  
	                try {  
	                    retBuf.append((char) Integer.parseInt(  
	                            unicodeStr.substring(i + 2, i + 6), 16));  
	                    i += 5;  
	                } catch (NumberFormatException localNumberFormatException) {  
	                    retBuf.append(unicodeStr.charAt(i));  
	                }  
	            else  
	                retBuf.append(unicodeStr.charAt(i));  
	        } else {  
	            retBuf.append(unicodeStr.charAt(i));  
	        }  
	    }  
	    return retBuf.toString();  
	}

	private static String buildJsonStr(RequestMsg requestMsg,String token){
		StringBuffer buf = new StringBuffer();
		buf.append(token);
		buf.append("action").append(requestMsg.getAction());
		buf.append("app_key").append(requestMsg.getApp_key());
		String data = "";
		if(requestMsg.getData() != null && StringUtils.isNotBlank(requestMsg.getData().toString())){
		    data = JSONObject.toJSONString(requestMsg.getData());
		}
		buf.append("data").append(data);
		buf.append("format").append(requestMsg.getFormat() == null?"":requestMsg.getFormat());
		buf.append("platform").append(requestMsg.getPlatform() == null?"":requestMsg.getPlatform());
		buf.append("sign_method").append(requestMsg.getSign_method() == null?"":requestMsg.getSign_method());
		buf.append("timestamp").append(requestMsg.getTimestamp() == null?"":requestMsg.getTimestamp());
		buf.append("version").append(requestMsg.getVersion() == null?"":requestMsg.getVersion());
		buf.append(token);
		return buf.toString();
	}
}
